const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: process.env.DB_HOST || "43.143.253.188",
  port: parseInt(process.env.DB_PORT || "3306", 10),
  user: process.env.DB_USER || "nextjs",
  password: process.env.DB_PASS || "yEAiRE2jcxTyRBy5",
  database: process.env.DB_NAME || "nextjs",
  charset: 'utf8mb4',
  timezone: '+08:00',
};

async function checkCasinoRounds() {
  let connection;
  
  try {
    console.log('🔍 检查娱乐城期数状态...');
    
    // 连接数据库
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功！');
    
    // 检查大小期数表
    console.log('\n📋 检查大小期数表 (casino_dice_rounds):');
    const [diceTables] = await connection.execute("SHOW TABLES LIKE 'casino_dice_rounds'");
    if (diceTables.length > 0) {
      const [diceRounds] = await connection.execute(`
        SELECT id, status, num1, num2, num3, start_time, end_time, created_at
        FROM casino_dice_rounds 
        ORDER BY id DESC 
        LIMIT 5
      `);
      
      console.log('🎲 最近5个大小期数:');
      diceRounds.forEach(round => {
        const statusText = { 0: '下注中', 1: '开奖中', 2: '已结算' }[round.status] || `未知(${round.status})`;
        console.log(`  ID: ${round.id}, 状态: ${statusText}, 结果: ${round.num1},${round.num2},${round.num3}, 开始: ${round.start_time}, 结束: ${round.end_time}`);
      });
    } else {
      console.log('❌ casino_dice_rounds 表不存在');
    }
    
    // 检查赤壁期数表
    console.log('\n📋 检查赤壁期数表 (casino_chibi_rounds):');
    const [chibiTables] = await connection.execute("SHOW TABLES LIKE 'casino_chibi_rounds'");
    if (chibiTables && chibiTables.length > 0) {
      const [chibiRounds] = await connection.execute(`
        SELECT id, status, winning_side, battle_report, start_time, end_time, created_at
        FROM casino_chibi_rounds 
        ORDER BY id DESC 
        LIMIT 5
      `);
      
      console.log('⚔️ 最近5个赤壁期数:');
      chibiRounds.forEach(round => {
        const statusText = { 0: '下注中', 1: '开奖中', 2: '已结算' }[round.status] || `未知(${round.status})`;
        const sideText = { 1: '魏国', 2: '蜀国', 3: '吴国' }[round.winning_side] || `未知(${round.winning_side})`;
        console.log(`  ID: ${round.id}, 状态: ${statusText}, 获胜方: ${sideText}, 战报: ${round.battle_report || '无'}, 开始: ${round.start_time}, 结束: ${round.end_time}`);
      });
    } else {
      console.log('❌ casino_chibi_rounds 表不存在');
    }
    
    // 检查当前活跃期数
    console.log('\n🔍 检查当前活跃期数:');
    
    if (diceTables.length > 0) {
      const [currentDice] = await connection.execute(`
        SELECT id, status, start_time, end_time
        FROM casino_dice_rounds 
        WHERE status IN (0, 1)
        ORDER BY id DESC 
        LIMIT 1
      `);
      
      if (currentDice.length > 0) {
        const round = currentDice[0];
        const statusText = { 0: '下注中', 1: '开奖中' }[round.status];
        console.log(`🎲 当前大小期数: ID=${round.id}, 状态=${statusText}, 开始=${round.start_time}, 结束=${round.end_time}`);
      } else {
        console.log('🎲 没有活跃的大小期数');
      }
    }
    
    if (chibiTables && chibiTables.length > 0) {
      const [currentChibi] = await connection.execute(`
        SELECT id, status, start_time, end_time
        FROM casino_chibi_rounds 
        WHERE status IN (0, 1)
        ORDER BY id DESC 
        LIMIT 1
      `);
      
      if (currentChibi.length > 0) {
        const round = currentChibi[0];
        const statusText = { 0: '下注中', 1: '开奖中' }[round.status];
        console.log(`⚔️ 当前赤壁期数: ID=${round.id}, 状态=${statusText}, 开始=${round.start_time}, 结束=${round.end_time}`);
      } else {
        console.log('⚔️ 没有活跃的赤壁期数');
      }
    }
    
    // 检查是否有状态异常的期数
    console.log('\n⚠️ 检查状态异常的期数:');
    
    if (diceTables.length > 0) {
      const [abnormalDice] = await connection.execute(`
        SELECT id, status, num1, num2, num3
        FROM casino_dice_rounds 
        WHERE status = 1 AND (num1 IS NULL OR num2 IS NULL OR num3 IS NULL)
        ORDER BY id DESC
      `);
      
      if (abnormalDice.length > 0) {
        console.log('🎲 发现开奖中但结果不完整的大小期数:');
        abnormalDice.forEach(round => {
          console.log(`  ID: ${round.id}, 结果: ${round.num1},${round.num2},${round.num3}`);
        });
      } else {
        console.log('🎲 没有发现异常的大小期数');
      }
    }
    
    if (chibiTables && chibiTables.length > 0) {
      const [abnormalChibi] = await connection.execute(`
        SELECT id, status, winning_side, battle_report
        FROM casino_chibi_rounds 
        WHERE status = 1 AND (winning_side IS NULL OR winning_side < 1 OR winning_side > 3)
        ORDER BY id DESC
      `);
      
      if (abnormalChibi.length > 0) {
        console.log('⚔️ 发现开奖中但结果不完整的赤壁期数:');
        abnormalChibi.forEach(round => {
          console.log(`  ID: ${round.id}, 获胜方: ${round.winning_side}, 战报: ${round.battle_report}`);
        });
      } else {
        console.log('⚔️ 没有发现异常的赤壁期数');
      }
    }
    
  } catch (error) {
    console.error('❌ 检查过程中发生错误:', error);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 执行检查
if (require.main === module) {
  checkCasinoRounds()
    .then(() => {
      console.log('✅ 检查完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('❌ 检查失败:', error);
      process.exit(1);
    });
}

module.exports = { checkCasinoRounds };
